package com.inool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.inool.mapper.SysRoleMenuMapper;
import com.inool.util.MenuHelper;
import com.inool.common.exception.InoolException;
import com.inool.model.SysMenu;
import com.inool.mapper.SysMenuMapper;
import com.inool.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inool.model.SysRoleMenu;
import com.inool.vo.AssignMenuVo;
import com.inool.vo.MetaVo;
import com.inool.vo.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 5unkzh1
 * @since 2024-02-04
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        //全部权限列表
        List<SysMenu> sysMenuList = this.list();
        if (CollectionUtils.isEmpty(sysMenuList)) return null;

        //构建树形数据
        List<SysMenu> result = MenuHelper.buildTree(sysMenuList);
        return result;
    }

    @Override
    public boolean removeMenuById(String id) {
        int count = this.count(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, id));
        if (count > 0) {
            throw new InoolException(201, "菜单不能删除");
        }
        sysMenuMapper.deleteById(id);
        return false;
    }

    @Transactional
    @Override
    public void doAssign(AssignMenuVo assginMenuVo) {
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleCode, assginMenuVo.getRoleCode()));

        List<String> menuIdList = assginMenuVo.getMenuIdList();
        if (menuIdList != null) {
            for (String menuId : menuIdList) {
                // 检查 Long 类型的值是否为 null
                if (menuId == null) continue;
                SysRoleMenu rolePermission = new SysRoleMenu();
                rolePermission.setRoleCode(assginMenuVo.getRoleCode());
                rolePermission.setMenuId(menuId);
                sysRoleMenuMapper.insert(rolePermission);
            }
        }
    }

    @Override
    public List<SysMenu> findSysMenu() {
        //全部权限列表
        List<SysMenu> allSysMenuList = this.list();     

        List<SysMenu> sysMenuList = MenuHelper.buildTree(allSysMenuList);
        return sysMenuList;
    }

    @Override
    public List<SysMenu> findSysMenuByRoleCode(String roleCode) {
        //全部权限列表
        List<SysMenu> allSysMenuList = sysMenuMapper.findMenusByRoleCode(roleCode);


        //根据角色id获取角色权限
        List<SysRoleMenu> sysRoleMenuList = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleCode, roleCode));
        //转换给角色id与角色权限对应Map对象
        List<String> menuIdList = sysRoleMenuList.stream().map(e -> e.getMenuId()).collect(Collectors.toList());

        allSysMenuList.forEach(permission -> {
            if (menuIdList.contains(permission.getId())) {
                permission.setSelect(true);
            } else {
                permission.setSelect(false);
            }
        });

 

        List<SysMenu> sysMenuList = MenuHelper.buildTree(allSysMenuList);
        return sysMenuList;
    }




    @Override
    public List<RouterVo> findUserMenuList(Long userId) {
        List<SysMenu> sysMenuList=null;
        if(userId.longValue()==1){
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
            sysMenuList = baseMapper.selectList(wrapper);
        }else{
            //如果不是管理员根据id查询
            sysMenuList = baseMapper.findMenuListByUserId(userId);

        }
        //构建菜单
        List<SysMenu> sysMenuTreeList   =    MenuHelper.buildTree(sysMenuList);
        //使用构建成框架要求的路由结构
        List<RouterVo> routerVoList=this.buildRouter(sysMenuTreeList);
        return routerVoList;
    }

    private List<RouterVo> buildRouter(List<SysMenu> menus) {
        //创建list集合 用于存储最终数据
        List<RouterVo> routers =new ArrayList<>();
        for(SysMenu menu:menus){
            RouterVo router = new RouterVo();
            router.setHidden(false);
            router.setAlwaysShow(false);
            router.setPath(getRouterPath(menu));
            router.setComponent(menu.getComponent());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            //下一层数据部分
            List<SysMenu> children = menu.getChildren();
            if(menu.getRequiresAuth().intValue()==1){
                //加载出来下面隐藏路由
                List<SysMenu> hiddenMenuList = children.stream().filter(item ->StringUtils.isEmpty(item.getComponent()))
                        .collect(Collectors.toList());
                for(SysMenu hiddenMenu : hiddenMenuList){
                    RouterVo hiddenRouter = new RouterVo();
                    hiddenRouter.setHidden(true);
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getRouterPath(hiddenMenu));
                    hiddenRouter.setComponent(hiddenMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(hiddenMenu.getName(), hiddenMenu.getIcon()));
                    routers.add(hiddenRouter);
                }
            }else {
                if(!CollectionUtils.isEmpty(children)){
                    if(children.size() > 0) {
                        router.setAlwaysShow(true);
                    }
                    //递归
                    router.setChildren(buildRouter(children));
                }
            }
            routers.add(router);
        }


        return routers;
    }

    /**
    
    @Override
    public List<String> findUserPerms(Long userId) {
        List<SysMenu> sysMenuList=null;
        if(userId.longValue()==1){
            LambdaQueryWrapper<SysMenu> wrapper=new LambdaQueryWrapper<>();
            sysMenuList=baseMapper.selectList(wrapper);
        }else{
            //不是管理
            sysMenuList = baseMapper.findMenuListByUserId(userId);
        }
        List<String> perms = sysMenuList.stream()
                .filter(item->item.getRequiresAuth()==2)                
                .collect(Collectors.toList());
        return perms;
    }
         * 
   
     */

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = "/" + menu.getPath();
        if(menu.getParentId() != "0" || menu.getParentId()!=null) {
            routerPath = menu.getPath();
        }
        return routerPath;
    }

    @Override
    public IPage<SysMenu> pageSysMenu(IPage<SysMenu> page) {
        return page(page);
  }

  
}